﻿using System;
using System.Diagnostics.Contracts;
using System.Windows.Data;

namespace AnthStat.WPF.Applications.Converters
{
    [ValueConversion(typeof(double), typeof(double))]
    public sealed class PoundsToKilogramsConverter : IValueConverter
    {
        private const double POUNDS_TO_KILOS = 0.45359237;
        private const double KILOS_TO_POUNDS = 2.20462262;

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null || String.IsNullOrEmpty(value.ToString())) return Double.NaN;

            double weight = System.Convert.ToDouble(value);

            if (Double.IsNaN((weight)))
            {
                return Double.NaN;
            }

            Contract.Assert(weight >= 0);

            return Math.Round(weight * KILOS_TO_POUNDS, 2);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null || String.IsNullOrEmpty(value.ToString())) return Double.NaN;

            double weight = System.Convert.ToDouble(value);
            Contract.Assert(weight >= 0);

            return Math.Round(weight * POUNDS_TO_KILOS, 2);
        }
    }
}
